<template>
  <div class="container">
    <van-nav-bar title="返工返修检录入" fixed class="titleStyle" left-arrow @click-left="onClickLeft" />
    <!-- <div class="saveBtnDiv">
      <van-button class="saveBtns" type="primary" native-type="submit" @click="badModel = true">报废</van-button>
      <van-button class="saveBtns" style="margin-right:5px ;" type="primary" native-type="submit" @click="submitForm(1)">提交</van-button>
    </div> -->
    <div class="publicBox formStyle">
      <van-row type="flex" justify="end" style="margin-bottom:10px;">
        <van-button style="margin-right:5px;" size="small" type="info" native-type="submit" :disabled="!ruleForm.reworkRepairNo" @click="badModel = true">报废品登记</van-button>
        <van-button style="width:80px" size="small" type="info" native-type="submit" :disabled="!ruleForm.reworkRepairNo" @click="submitForm">提 交</van-button>
      </van-row>
      <van-cell-group style="margin-bottom:5px;">
        <van-field v-model="reworkRepairNo" label="返工返修单号" placeholder="请扫描返工返修单号" right-icon="scan" @click-right-icon="scan" @keyup.enter.native="getDataByreworkNo(reworkRepairNo)" />
      </van-cell-group>
      <div v-if="isShowForm" class="inputBox">
        <div style="margin-bottom:5px;">
          <van-form class="vanForm" label-width="80px" label-align="right">
            <van-collapse v-model="activeNames">
              <van-collapse-item name="1">
                <template #title>
                  <div>
                    工单批次号
                    <span style="margin-left:20px;">{{ ruleForm.planBatchNo }}</span>
                  </div>
                </template>
                <van-row>
                  <van-col :span="12">
                    <van-field v-model="ruleForm.reworkFactoryName" readonly label="产线" />
                  </van-col>
                  <van-col :span="12">
                    <van-field v-model="ruleForm.factoryName" readonly label="工位" />
                  </van-col>
                  <van-col :span="12">
                    <van-field v-model="ruleForm.procedureName" readonly label="工序" />
                  </van-col>
                  <van-col :span="12">
                    <van-field v-model="ruleForm.equipName" readonly label="设备" />
                  </van-col>
                  <van-col :span="12">
                    <van-field :value="ruleForm.num" readonly label="可检数量" />
                  </van-col>
                  <van-col :span="12">
                    <van-field :value="ruleForm.checkNum" readonly label="检验数量" />
                  </van-col>
                  <van-col :span="12">
                    <van-field v-model="ruleForm.qualifiedNum" label="合格数" placeholder="请输入合格数" />
                  </van-col>
                  <van-col :span="12">
                    <van-field :value="ruleForm.discardNum" readonly type="digit" label="报废数" />
                  </van-col>
                  <van-col :span="24">
                    <van-field v-model="ruleForm.remark" placeholder="请输入备注" label="备注" rows="3" size="mini" type="textarea" maxlength="200" show-word-limit />
                  </van-col>
                  <van-col :span="24">
                    <van-field v-model="ruleForm.checkName" size="mini" label="检验人" readonly @click="showUser = true" />
                  </van-col>
                  <van-col :span="24">
                    <van-field v-model="ruleForm.checkAt" label="检验时间" class="mustInput" @focus="showTime = true" />

                  </van-col>
                  <van-col :span="24">
                    <van-field name="uploader" label="文件上传" class="mustInput">
                      <template #input>
                        <van-uploader v-model="ruleForm.fileList" multiple :max-count="5" :after-read="afterRead()" :max-size="5242880" accept="image/jpeg ,image/png" @oversize="onOversize" />
                      </template>
                    </van-field>
                  </van-col>
                </van-row>
              </van-collapse-item>
            </van-collapse>
          </van-form>
        </div>
      </div>

    </div>
    <!-- 人员选择 -->
    <van-popup v-model="showUser" position="bottom">
      <van-picker title="人员选择" show-toolbar :columns="userList" @confirm="onConfirm" @cancel="showUser = false" />
    </van-popup>

    <!--  时间选择 -->
    <van-popup v-model="showTime" position="bottom" :style="{ height: '30%' }">
      <van-datetime-picker v-model="currentDate" type="datetime" @confirm="onTimeChange" @cancel="showTime = false" />
    </van-popup>

    <!-- 不良品登记 -->
    <van-popup v-model="badModel" position="right" :style="{ height: '100%',width:'100%' }">
      <badModel ref="badModel" :bad-model.sync="badModel" @getEntry="getEntry" />
    </van-popup>
  </div>
</template>
<script>
import badModel from './badModel'
import { myFunction } from '@/utils/function'
export default {
  name: 'RepairAndRework',
  components: { badModel },
  data () {
    return {
      reworkRepairNo: '',
      activeNames: ['1'], // 表单折叠面板
      ruleForm: {
        isReport: ''
      },
      loading: false,
      isShowForm: false, // 未发起请求时不展示所有内容
      showUser: false,
      userList: [],
      userLists: [],
      showTime: false,
      currentDate: new Date(),
      badModel: false,
      loginInfo: localStorage.getItem('padUserInfo') ? JSON.parse(localStorage.getItem('padUserInfo')).data : {}
    }
  },
  watch: {
    ruleForm: {
      deep: true,
      handler (val) {
        const { qualifiedNum, discardNum } = val
        this.ruleForm.checkNum = Number(qualifiedNum || 0) + Number(discardNum || 0)
      }
    }
  },
  created () {
    const { code } = this.$route.params
    if (code) {
      this.planBatchNo = this.$route.params.code
      this.getDataByreworkNo(code)
    }
  },
  async mounted () {
    await this.getUser()
  },
  methods: {
    /**
 * @description: 根据返工单号查询信息
 * @param {*} reworkNo
 * @return {*}
 */
    async getDataByreworkNo (reworkRepairNo) {
      const toast = this.$toast.loading({
        duration: 0, // 持续展示 toast
        message: '数据加载中...',
        forbidClick: true,
        loadingType: 'spinner'
      })
      setTimeout(() => {
        toast.clear()
      }, 500)
      const res = await this.$axios.post(`/dobo-product/pro/rework/repair/inspection/record/getReWorkReportByReworkRepairNo`, { reworkRepairNo: reworkRepairNo })
      if (res.data.code === 200) {
        console.log(res.data.data)
        const { userName, userId } = this.loginInfo
        const { reworkFactoryName, equipName, equipId, reworkFactoryId, reworkBatchNo } = res.data.data
        this.ruleForm = {
          ...res.data.data,
          reworkRepairNo,
          planBatchNo: reworkBatchNo,
          checkName: userName,
          checkBy: userId,
          checkAt: myFunction(new Date()),
          checkNum: null,
          qualifiedNum: 0,
          discardNum: 0,
          proLineName: reworkFactoryName,
          proLineId: reworkFactoryId,
          equName: equipName,
          equId: equipId
        }
      }
      this.isShowForm = true
    },
    getEntry (data) {
      const badNumList = []
      const defectList = []
      data.forEach((item, index) => {
        badNumList.push(+item.num)
        const { num } = item
        item.discardNum = num
        // item.defectsList.forEach(itx => {
        //   console.log(index)
        //   defectList.push({ ...itx, discardNum: num, idx: index + 1 })
        // })
      })
      this.ruleForm.discardNum = badNumList.length ? this.sum(badNumList) : 0
      const { qualifiedNum, discardNum } = this.ruleForm
      this.ruleForm.checkNum = Number(qualifiedNum || 0) + Number(discardNum || 0)
      this.ruleForm.defectList = data
      console.log(this.ruleForm)
    },
    /**
     * @description: 求和
     * @param {*} arr
     * @return {*}
     */
    sum (arr) {
      return arr.reduce((prev, curr) => Number(prev) + Number(curr), 0)
    },
    /* 获取所有人员 */
    async getUser () {
      const res = await this.$axios.get('/dobo-user/user/getAllUser')
      if (res.data.code === 200) {
        this.userLists = res.data.data
        res.data.data.forEach((item) => {
          this.userList.push(item.name)
        })
      }
    },
    /* 人员选择 */
    onConfirm (e) {
      let id = ''
      this.userLists.forEach((item) => {
        if (item.name === e) id = item.id
      })
      this.ruleForm.checkBy = id
      this.ruleForm.checkName = e
      this.showUser = false
    },
    /* 时间选择赋值 */
    onTimeChange (value) {
      this.ruleForm.checkAt = myFunction(value)
      this.showTime = false
    },
    /**
     * @description: 扫码
     * @param {*} e
     * @return {*}
     */
    scan () {
      this.$router.push('/saomaShow?name=返工返修检')
    },
    onOversize (file) {
      this.$toast.fail('文件大小不能超过 5M')
    },
    // 上传图片
    afterRead (items, type) {
      return file => {
        if (file) {
          if (file.constructor === Object) file = [file]
          const toast = this.$toast.loading({
            duration: 0, // 持续展示 toast
            message: '图片上传中...',
            forbidClick: true,
            loadingType: 'spinner'
          })
          file.filter((item, index) => {
            const form = new FormData()
            form.append('file', item.file)
            this.$axios.post('/dobo-file/files-anon', form).then(res => {
              if (res.data.code === 200) {
                item.fileId = res.data.data.id
                item.fileUrl = res.data.data.url
                item.fileName = res.data.data.name
                if (++index === file.length) {
                  toast.clear()
                }
              } else {
                this.$toast.fail(res.data.msg)
                toast.clear()
              }
            })
          })
        }
      }
    },
    // 提交表单
    submitForm () {
      this.$dialog
        .confirm({
          title: '提示',
          message: '是否确认提交？'
        })
        .then(() => {
          console.log(this.ruleForm)
          const { checkNum, qualifiedNum, discardNum, num } = this.ruleForm
          if (!checkNum || checkNum < 1) {
            return this.$dialog.alert({ title: '提示', message: '检验数不能小于1,请维护合格数、报废数！' })
          } else if (checkNum > num) {
            return this.$dialog.alert({ title: '提示', message: '检验数不能大于可检数量！' })
          } else {
            this.submitApi(this.ruleForm)
          }
        })
        .catch(() => {
          return false
        })
    },
    submitApi (params) {
      this.$axios
        .post('/dobo-product/pro/rework/repair/inspection/record/save', params)
        .then((res) => {
          if (res.data.code === 200) {
            this.$dialog
              .alert({
                title: '提示',
                message: '提交成功!'
              })
              .then(() => {
                window.location.reload()
              })
              .catch(() => { })
          } else {
            this.$toast.fail(res.data.msg)
            setTimeout(() => {
              window.location.reload()
            }, 1000)
          }
        })
    },
    // 返回
    onClickLeft () {
      const { query } = this.$route
      if (query.path) {
        this.$router.push(`/${query.path}`)
      } else {
        this.$router.push('/task')
      }
    }
  }
}
</script>
<style lang='scss' scoped>
.container {
  .saveBtnDiv {
    position: absolute;
    right: 10px;
    top: 10px;
    width: 200px;
    height: 40px;
    text-align: right;
  }
  .publicBox {
    .vanForm {
      .van-field {
        border-bottom: 1px solid #ebedf0;
      }
      .zhedie {
        height: 45px;
        line-height: 45px;
        background: green;
        width: 100%;
        text-align: center;
      }
    }
  }
  .qualityContent {
    height: calc(100% - 270px);
    overflow: hidden;
    h1 {
      height: 40px;
      line-height: 40px;
      font-weight: normal;
      text-align: center;
      background: #eeee;
      color: #022566;
    }
    .contentItem {
      height: calc(100% - 40px);
      overflow-y: auto;
    }
  }
}
</style>
<style lang='scss'>
// 提交按钮样式
.saveBtnDiv {
  .saveBtns {
    float: right;
    font-size: 16px;
    z-index: 102;
    height: 40px;
    line-height: 40px;
    background: linear-gradient(to top right, #1cacff, #022566);
    border: 1px solid #022566;
    padding: 0 12px;
    .van-button__content {
      display: block;

      .van-button__text {
        text-align: center;
        width: 100%;
        font-size: 20px;
      }
    }
  }
}
</style>
